//
//  WDCarTypeController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/19.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDCarTypeController.h"
#import "WDCarListCell.h"
#import "WDCarList.h"
#import "WDCarListView.h"
#import "WDStseries.h"
#import "WDFirstSort.h"

@interface WDCarTypeController () <UITableViewDelegate, UITableViewDataSource, WDCarListViewDelegate>
/** tableView */
@property (nonatomic, strong) UITableView *carTableView;
/** 车品牌数组 */
@property (nonatomic, strong) NSMutableArray *carArr;
/** 排序后的数组 */
@property (nonatomic, strong) NSArray *dataArr;
/** 车系控制器 */
@property (nonatomic, strong) WDCarListView *carListView;

@end

@implementation WDCarTypeController

#pragma mark - lazy load
- (UITableView *)carTableView
{
    if (!_carTableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, WDScreenH - 64) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        
        //设置索引字体颜色
        tableView.sectionIndexColor = ColorForRGB(0x6b6b6b);
        //设置索引背景颜色
        tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        
        _carTableView = tableView;
    }
    return _carTableView;
}

- (WDCarListView *)carListView
{
    if (!_carListView) {
        
        _carListView = [[WDCarListView alloc] initWithFrame:CGRectMake(WDScreenW, 64, self.view.frame.size.width, self.view.frame.size.height)];
        
        _carListView.delegate = self;
        
        [[UIApplication sharedApplication].keyWindow addSubview:_carListView];
        
        [UIView animateWithDuration:0.3 animations:^{
            
            _carListView.frame = CGRectMake(80, 64, self.view.frame.size.width, self.view.frame.size.height);
        }];
        
    }
    return _carListView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadNavItemWithAction:@selector(backBtn) btnImage:@"icon_back" btnSelImage:@"icon_back" title:@"车辆品牌"];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //解档车品牌信息
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *archiverPath = [path stringByAppendingPathComponent:WDCarListFile];
    
    self.carArr = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath];
    
    //排序车型
    self.carArr = (NSMutableArray *)[self.carArr sortedArrayUsingComparator:^NSComparisonResult(WDCarList *obj1,WDCarList *obj2) {
        
        return [obj1.start_with compare:obj2.start_with];
        
    }];
    
    //分好组的字典数组
    NSArray *dataArr = [WDFirstSort firstSortWithObjectArray:self.carArr];
    
    self.dataArr = dataArr;
    
    [self.view addSubview:self.carTableView];
    
}

- (void)backBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 获取车系信息
- (void)getCarWithBrandId:(WDCarList *)carList
{
    //解档车系信息
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *archiverPath = [path stringByAppendingPathComponent:WDCarSeriesFile];
    
    NSArray *carLists = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath];
    
    NSMutableArray *stseries = [NSMutableArray array];
    
    for (WDStseries *tempStser in carLists) {
        
        if ([tempStser.brand_id isEqualToString:carList.id]) {
            [stseries addObject:tempStser];
        }
    }
    
    self.carListView.carList = stseries;
    //把品牌名传过去
    self.carListView.brand_name = carList.name;
}

#pragma mark - WDCarListDelegate
- (void)popViewWithSeries:(WDStseries *)series brandName:(NSString *)brandName
{
    [self tapDismiss];
    
    if (self.carType) {
        
        self.carType(series, brandName);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dict = self.dataArr[section];
    NSMutableArray *array = dict[@"content"];
    return [array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDCarListCell *cell = [WDCarListCell carListCellWithTableView:tableView];
    
    NSDictionary *dict = self.dataArr[indexPath.section];
    NSArray *carLists = dict[@"content"];
    
    cell.carList = carLists[indexPath.row];
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, 20)];
    headView.backgroundColor = ColorForRGB(0xf0f1f2);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, WDScreenW, 20)];
    
    NSDictionary *dict = self.dataArr[section];
    NSString *title = dict[@"firstLetter"];
    label.text = title;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = ColorForRGB(0x6b6b6b);
    [headView addSubview:label];
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSDictionary *dict in self.dataArr) {
        NSString *title = dict[@"firstLetter"];
        [resultArray addObject:title];
    }
    return resultArray;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dict = self.dataArr[indexPath.section];
    NSArray *carLists = dict[@"content"];
    
    WDCarList *tempCar = carLists[indexPath.row];//找到点击的品牌
    
    UIView *cover = [[UIView alloc] initWithFrame:CGRectMake(0, 64, WDScreenW, WDScreenH)];
    
    cover.tag = 100;
    
    cover.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    
    [[UIApplication sharedApplication].keyWindow addSubview:cover];
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDismiss)];
    
    [cover addGestureRecognizer:tap];
    
    [self getCarWithBrandId:tempCar];
    
}

- (void)tapDismiss
{
    for (UIView *childView in [[UIApplication sharedApplication].keyWindow subviews]) {
        if (childView.tag == 100 || [childView isKindOfClass:[WDCarListView class]]) {
            
            [childView removeFromSuperview];
            
            self.carListView = nil;
            
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
